package com.lc.ibps.platform.rest.bpmn;

import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;
import com.lc.ibps.api.base.query.QueryFilter;
import com.lc.ibps.api.base.query.QueryOP;
import com.lc.ibps.base.core.exception.BaseException;
import com.lc.ibps.base.core.util.AppUtil;
import com.lc.ibps.base.core.util.json.JsonUtil;
import com.lc.ibps.base.core.util.string.StringUtil;
import com.lc.ibps.base.framework.page.PageList;
import com.lc.ibps.base.web.context.ContextUtil;
import com.lc.ibps.bpmn.builder.BpmTaskChangeBuilder;
import com.lc.ibps.bpmn.domain.BpmTaskChange;
import com.lc.ibps.bpmn.persistence.entity.BpmTaskChangeAssignPo;
import com.lc.ibps.bpmn.persistence.entity.BpmTaskChangePo;
import com.lc.ibps.bpmn.persistence.entity.BpmTaskPo;
import com.lc.ibps.bpmn.repository.BpmTaskChangeRepository;
import com.lc.ibps.bpmn.repository.BpmTaskRepository;
import com.lc.ibps.cloud.entity.APIPageList;
import com.lc.ibps.cloud.entity.APIRequest;
import com.lc.ibps.cloud.entity.APIResult;
import com.lc.ibps.web.controller.BaseApiController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;

@RequestMapping(value = "/api/webapi/bpmTaskChangeService")
@Api( value = "/bpmTaskChangeService",tags = "流程管理-流程转办服务")
@RestController("bpmTaskChangeRest")
public class BpmTaskChangeController extends BaseApiController {
	
	private BpmTaskRepository bpmTaskRepository;
	private BpmTaskChangeRepository bpmTaskChangeRepository;

	public BpmTaskChangeController() {
		bpmTaskRepository = AppUtil.getBean(BpmTaskRepository.class);
		bpmTaskChangeRepository = AppUtil.getBean(BpmTaskChangeRepository.class);
	}
	
	@ApiOperation(value = "获取转办代理列表", notes = "获取转办代理列表")
	@RequestMapping(value="listJson", method=RequestMethod.POST)
	public APIResult<APIPageList<BpmTaskChangePo>> listJson(
			@ApiParam(name = "request", value = "传入查询请求json字符串", required = true) @RequestBody(required = true) APIRequest request) {
		APIResult<APIPageList<BpmTaskChangePo>> result = new APIResult<>();
		QueryFilter queryFilter = getQuerFilter(request);
		if(!ContextUtil.getCurrentUser().isSuper()){
			queryFilter.addFilter("OWNER_ID_", ContextUtil.getCurrentUserId(), QueryOP.EQUAL);
		}
		try {
			PageList<BpmTaskChangePo> bpmTaskChangeList=(PageList<BpmTaskChangePo>)bpmTaskChangeRepository.query(queryFilter);
			BpmTaskChangeBuilder.build(bpmTaskChangeList);
			APIPageList<BpmTaskChangePo> pageList = getAPIPageList(bpmTaskChangeList);
			result.setData(pageList);
			result.setMessage("获取转办代理列表成功");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR,"获取转办代理列表失败", e);
		}
		return result;
	}
	
	@ApiOperation(value = "获取转办信息", notes = "获取转办信息")
	@RequestMapping(value="toDelegate", method=RequestMethod.GET)
	public APIResult<Map<String, Object>> toDelegate(
			@RequestParam(name = "id", required = false) @ApiParam(name = "id", value = "ID", required = false) String id,
			@RequestParam(name = "taskId", required = false) @ApiParam(name = "taskId", value = "任务ID", required = false) String taskId) {
		APIResult<Map<String, Object>> result = new APIResult<>();
		try {
//			validatePression(taskId, ActionType.REJECT_TO_PREVIOUS.getKey());
			
			if(StringUtil.isEmpty(id)&&StringUtil.isEmpty(taskId)){
				throw new BaseException("参数不能都为空！");
			}

			BpmTaskChangePo bpmTaskChange=null;
			if(StringUtil.isNotEmpty(id)){
				bpmTaskChange=bpmTaskChangeRepository.loadCascade(id);
				BpmTaskChangeBuilder.build(bpmTaskChange);
			}else if(StringUtil.isNotEmpty(taskId)){
				BpmTaskPo bpmTask = bpmTaskRepository.get(taskId);
				bpmTaskChange = BpmTaskChangeBuilder.build(bpmTask, BpmTaskChangePo.CHANGE_SHIFT, BpmTaskChangePo.COMMENT_SHIFT_DEF, ContextUtil.getCurrentUser());
			}

			Map<String, Object> data = Maps.newHashMap();
			data.put("taskId", taskId);
			data.put("bpmTaskChange", bpmTaskChange);
			result.setData(data);
			result.setMessage("获取转办信息成功");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "获取转办信息失败", e);
		}
		return result;
	}
	
	@ApiOperation(value = "获取转办代理信息", notes = "获取转办代理信息")
	@RequestMapping(value="get", method=RequestMethod.GET)
	public APIResult<Map<String, Object>> get(
			@RequestParam(name = "id", required = true) @ApiParam(name = "id", value = "ID", required = true) String id) {
		APIResult<Map<String, Object>> result = new APIResult<>();
		try {
			BpmTaskChangePo bpmTaskChange=null;
			if(StringUtil.isNotEmpty(id)){
				bpmTaskChange=bpmTaskChangeRepository.loadCascade(id);
				BpmTaskChangeBuilder.build(bpmTaskChange);
			}
			Map<String, Object> data = Maps.newHashMap();
			data.put("bpmTaskChange", bpmTaskChange);
			result.setData(data);
			result.setMessage("获取转办代理信息成功");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "获取转办代理信息失败", e);
		}
		return result;
	}
	
	/** 
	 * 保存【流程任务变更】信息
	 *
	 * @param request
	 * @param response
	 * @param  bpmTaskChange
	 * @throws Exception
	 */
	@ApiOperation(value = "保存任务变更信息", notes = "保存任务变更信息")
	@RequestMapping(value="save", method = RequestMethod.POST)
	public APIResult<String> save(
			@ApiParam(name = "json", value = "传入查询请求json字符串", required = true) 
			@RequestParam(required = true) String json) {
		APIResult<String> result = new APIResult<>();
		try {
			BpmTaskChangePo bpmTaskChangePo = getFromRequest(json);
			//构造领域对象和保存数据
			BpmTaskChange bpmTaskChange =bpmTaskChangeRepository.newInstance(bpmTaskChangePo);
			bpmTaskChange.shift(ContextUtil.getCurrentUserId());
			result.setMessage("保存流程任务变更成功");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "对流程任务变更操作失败", e);
		}
		return result;
	}
	
	/**
	 * 设置【流程任务变更】状态
	 *
	 * @param id
	 * @param status
	 * @return
	 */
	@ApiOperation(value = "流程任务变更状态", notes = "流程任务变更状态")
	@RequestMapping(value="setStatus", method = RequestMethod.POST)
	public APIResult<String> setStatus(
			@RequestParam(name = "id", required = true) @ApiParam(name = "id", required = true) String id,
			@RequestParam(name = "status", required = false) @ApiParam(name = "status", required = false) String status) {
		APIResult<String> result = new APIResult<>();
		try {
			status = StringUtil.isNotEmpty(status)?status:BpmTaskChangePo.CHANGE_STATUS_CANCEL;
			if(StringUtil.isNotEmpty(id)){
				BpmTaskChangePo bpmTaskChangePo = bpmTaskChangeRepository.get(id);
				bpmTaskChangePo.setStatus(status);
				BpmTaskChange bpmTaskChange =bpmTaskChangeRepository.newInstance(bpmTaskChangePo);
				bpmTaskChange.unshift(ContextUtil.getCurrentUserId());
			}
			result.setMessage("流程任务变更状态成功");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "对流程任务变更状态失败", e);
		}
		return result;
	}
	
	/** 
	 * 获取表单数据
	 *
	 * @param request
	 */
	private BpmTaskChangePo getFromRequest(String json){
		JSONObject jsonObj = JSONObject.fromObject(json);
		
		List<BpmTaskChangeAssignPo> bpmTaskChangeAssignPoList = getBpmTaskChangeAssignPoList(jsonObj);
		BpmTaskChangePo bpmTaskChangePo = getBpmTaskChangePo(jsonObj);
		bpmTaskChangePo.setBpmTaskChangeAssignPoList(bpmTaskChangeAssignPoList);

		return bpmTaskChangePo;
	}
	
	/** 
	 * 获取流程任务变更数据
	 *
	 * @param jsonObj
	 */
	private BpmTaskChangePo getBpmTaskChangePo(JSONObject jsonObj){
		if(StringUtil.isBlank(jsonObj.getString("completeTime"))){
			jsonObj.put("completeTime", null);
		}
		BpmTaskChangePo bpmTaskChangePo = (BpmTaskChangePo) JsonUtil.getDTO(jsonObj.toString(), BpmTaskChangePo.class);
		return bpmTaskChangePo;
	}
	
	/** 
	 * 获取任务变更候选人数据
	 *
	 * @param jsonObj
	 */
	@SuppressWarnings("unchecked")
	private List<BpmTaskChangeAssignPo> getBpmTaskChangeAssignPoList(JSONObject jsonObj){
		if(!jsonObj.containsKey("bpmTaskChangeAssignPoList")){
			return null;
		}
		
		List<BpmTaskChangeAssignPo> rs = JsonUtil.getDTOList(
													jsonObj.getJSONArray("bpmTaskChangeAssignPoList").toString(), 
													BpmTaskChangeAssignPo.class);
		jsonObj.discard("bpmTaskChangeAssignPoList");
		return rs;
	}
}
